package com.one.rope.mvp.web.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.one.rope.mvp.web.business.entity.AdminUser;
import com.one.rope.mvp.web.business.entity.MemberInfo;
import com.one.rope.mvp.basecore.exception.BusinessDataException;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Weijian.liu
 * @desc 自定义ShiroRealm，实现AuthorizingRealm接口用户认证
 * @date 2018/12/18
 */
public class MyShiroRealm extends AuthorizingRealm {

  /**
   * 角色和对应权限添加
   */
  @Override
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    //添加角色和权限
    return null;
  }

  /**
   * 用户登录认证
   */
  @Override
  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
      throws AuthenticationException {
    String accountName = (String) token.getPrincipal();
    String password = new String((char[]) token.getCredentials());
    if(password.equals(GlobalConfig.USER_TOKEN_SIMULATE_PWD)){
      // 如果是小程序登录
      MemberInfo memberInfo = new MemberInfo().selectOne(new QueryWrapper<MemberInfo>().eq("wx_open_id", accountName));
      if (null == memberInfo) {
        throw new BusinessDataException("登录失败！");
      }
      AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(memberInfo, password, "oneRopeMvpUser");
      return authenticationInfo;
    }
    AdminUser user = new AdminUser().selectOne(new QueryWrapper<AdminUser>().eq("account", accountName).eq("password", password));
    if (null == user) {
      throw new BusinessDataException("账户或密码错误！");
    }
    AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user, password,
        "oneRopeMvpAdmin");
    return authenticationInfo;
  }

}
